package com.xiaomi.eco.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaomi.eco.dal.entity.EcoCompanyTaskListEntity;
import com.xiaomi.eco.dal.entity.EcoCompanyWebMappingEntity;
import com.xiaomi.eco.dal.entity.TbEcoApplicationCompanyEntity;
import com.xiaomi.eco.service.*;
import com.xiaomi.eco.utils.EcoRobotMethod;
import com.xiaomi.eco.utils.EcoServiceQualityAlarm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EcoTaskAboutExpireServiceImpl implements EcoTaskAboutExpireService {
    String overDueAlarmUrl = "https://open.f.mioffice.cn/open-apis/im/v1/messages?receive_id_type=user_id";


    private static ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    EcoCompanyTaskListEntityServiceImpl ecoCompanyTaskListEntityService;

    @Autowired
    private EcoCompanyWebMappingEntityService ecoCompanyWebMappingEntityService;

    @Autowired
    private TbEcoApplicationCompanyEntityService tbEcoApplicationCompanyEntityService;
    @Value("${Feishu2.appId}")
    private String appId2;

    @Value("${Feishu2.appSecret}")
    private String appSecret2;

    @Value("${Feishu.appId}")
    private String appId;

    @Value("${Feishu.appSecret}")
    private String appSecret;


    public String getTenantAccessToken(Long isSelfStudy) {
        String tenantAccessToken = "";
        if (isSelfStudy == 0) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String innerRequestTenantAccessToken = String.format(EcoServiceQualityAlarm.requestTenantAccessToken, appId2, appSecret2);
            String innerTenantAccessTokenResponse = EcoRobotMethod.postForObject(EcoServiceQualityAlarm.tenantAccessTokenUrl, innerRequestTenantAccessToken);
            JsonNode innerTenantAccessTokenResponJsonNode = null;
            System.out.println("走自研任务创建的机器人: "+innerTenantAccessTokenResponse);
            try {
                innerTenantAccessTokenResponJsonNode = objectMapper.readTree(innerTenantAccessTokenResponse);
            } catch (JsonProcessingException e) {
                log.error("获取内部机器人json解析失败: {}", innerTenantAccessTokenResponJsonNode);
            }
            tenantAccessToken = innerTenantAccessTokenResponJsonNode.get(EcoServiceQualityAlarm.tenantAccessToken).asText();
        } else if (isSelfStudy == 1) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String externalRequestTenantAccessToken = String.format(EcoServiceQualityAlarm.requestTenantAccessToken, appId, appSecret);
            String externalTenantAccessTokenResponse = EcoRobotMethod.postForObject(EcoServiceQualityAlarm.tenantAccessTokenUrl, externalRequestTenantAccessToken);
            System.out.println("走外部创建任务创建的机器人: "+externalTenantAccessTokenResponse);
            JsonNode externalTenantAccessTokenResponJsonNode = null;
            try {
                externalTenantAccessTokenResponJsonNode = objectMapper.readTree(externalTenantAccessTokenResponse);
            } catch (JsonProcessingException e) {
                log.error("获取外部机器人json解析失败: {}", externalTenantAccessTokenResponse);
            }
            tenantAccessToken = externalTenantAccessTokenResponJsonNode.get(EcoServiceQualityAlarm.tenantAccessToken).asText();
        }


        return tenantAccessToken;
    }

    public Long getisselfstudy(String principalCompany){
        List<TbEcoApplicationCompanyEntity> tbEcoApplicationCompanyEntityList = tbEcoApplicationCompanyEntityService.list();
        Map<String, TbEcoApplicationCompanyEntity> applicationMap = tbEcoApplicationCompanyEntityList.stream().collect(Collectors.toMap(TbEcoApplicationCompanyEntity::getCompanyName, Function.identity(), (v1, v2) -> v2));
        TbEcoApplicationCompanyEntity applicationEntity = applicationMap.get(principalCompany);
        return applicationEntity.getIsSelfStudy();
    }


    @Override
    public void taskAboutExpire() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        List<EcoCompanyTaskListEntity> ecoCompanyTaskListEntityList = ecoCompanyTaskListEntityService.list();
        for (EcoCompanyTaskListEntity ecoCompanyTaskListEntity : ecoCompanyTaskListEntityList) {
            Long isselfstudy = getisselfstudy(ecoCompanyTaskListEntity.getPrincipalCompany());
            String tenantAccessToken = getTenantAccessToken(isselfstudy);
            String endTimeStr = ecoCompanyTaskListEntity.getEndTime();
            // 将字符串转换为LocalDate
            LocalDate endTime = LocalDate.parse(endTimeStr, formatter);
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            long daysBetween = ChronoUnit.DAYS.between(today, endTime);
            // 比较日期 如何判断任务是否逾期
            if (endTime.isBefore(today) && ecoCompanyTaskListEntity.getTaskStatus().equals(EcoServiceQualityAlarm.COMPLETEING)) {
                //String openId = getOpenId(ecoCompanyTaskListEntity.getPrincipalPhone(), EcoServiceQualityAlarm.principalPhone);
                String userId = ecoCompanyTaskListEntityService.getUserId(ecoCompanyTaskListEntity.getPrincipalPhone(),EcoServiceQualityAlarm.principalPhone);
                String overDueAlarm = String.format(EcoServiceQualityAlarm.overDueAlarmTemp, userId, ecoCompanyTaskListEntity.getTaskName(), String.valueOf(Math.abs(daysBetween)), ecoCompanyTaskListEntity.getTaskUrl(), ecoCompanyTaskListEntity.getTaskName());
                String response = EcoRobotMethod.postForObject(tenantAccessToken, overDueAlarmUrl, overDueAlarm);

            }
        }
    }
}


